{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python循环控制：break与continue的深度解析\n",
    "\n",
    "## 一、基本概念：循环控制的「急停」与「跳跃」\n",
    "\n",
    "在Python循环结构（`while`/`for`）中，`break`和`continue`是两个核心控制语句，用于改变循环的默认执行流程：\n",
    "- **`break`**：立即终止当前循环，跳出循环体，后续迭代不再执行；\n",
    "- **`continue`**：跳过当前迭代的剩余代码，直接进入下一次迭代。\n",
    "\n",
    "二者的本质区别在于：`break`是「终止循环」，`continue`是「跳过本次迭代」。\n",
    "\n",
    "---\n",
    "\n",
    "## 二、核心语法与执行流程\n",
    "\n",
    "### 2.1 语法规则\n",
    "```python\n",
    "# while循环中的使用\n",
    "while 条件表达式:\n",
    "    代码块1\n",
    "    if 触发条件:\n",
    "        break  # 终止循环\n",
    "    代码块2\n",
    "    if 其他条件:\n",
    "        continue  # 跳过后续代码，进入下一次循环\n",
    "\n",
    "# for循环中的使用\n",
    "for 变量 in 可迭代对象:\n",
    "    代码块A\n",
    "    if 触发条件:\n",
    "        break\n",
    "    代码块B\n",
    "    if 其他条件:\n",
    "        continue\n",
    "```\n",
    "\n",
    "### 2.2 执行流程图解\n",
    "```mermaid\n",
    "flowchart TD\n",
    "    A[进入循环] --> B{条件检查/迭代}\n",
    "    B -- 真/有元素 --> C[执行循环体]\n",
    "    C --> D{是否触发break?}\n",
    "    D -- 是 --> E[终止循环] \n",
    "    D -- 否 --> F{是否触发continue?}\n",
    "    F -- 是 --> B \n",
    "    F -- 否 --> G[执行循环体剩余代码] --> B\n",
    "    B -- 假/无元素 --> H[正常退出循环]\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "## 三、示例代码：典型场景的实践\n",
    "\n",
    "### 3.1 查找目标值（`break`的典型应用）\n",
    "```python\n",
    "def find_target(target: int, numbers: list) -> int:\n",
    "    \"\"\"\n",
    "    在列表中查找目标值，找到后立即终止循环\n",
    "    :param target: 目标数值\n",
    "    :param numbers: 待搜索列表\n",
    "    :return: 目标索引（未找到返回-1）\n",
    "    \"\"\"\n",
    "    for index, num in enumerate(numbers):\n",
    "        if num == target:\n",
    "            print(f\"找到目标值{target}，索引为{index}\")\n",
    "            break  # 找到即终止循环，提升效率\n",
    "        print(f\"当前检查：索引{index}，值{num}\")\n",
    "    else:\n",
    "        # for-else结构：循环正常结束（未触发break）时执行\n",
    "        print(f\"未找到目标值{target}\")\n",
    "        return -1\n",
    "    return index\n",
    "\n",
    "# 测试\n",
    "nums = [1, 3, 5, 7, 9]\n",
    "find_target(5, nums)  # 输出：当前检查：索引0，值1；当前检查：索引1，值3；找到目标值5，索引为2\n",
    "```\n",
    "\n",
    "### 3.2 过滤无效数据（`continue`的典型应用）\n",
    "```python\n",
    "def filter_even(numbers: list) -> list:\n",
    "    \"\"\"\n",
    "    过滤列表中的奇数，仅保留偶数\n",
    "    :param numbers: 输入列表\n",
    "    :return: 偶数列表\n",
    "    \"\"\"\n",
    "    even_list = []\n",
    "    for num in numbers:\n",
    "        if num % 2 != 0:\n",
    "            continue  # 跳过奇数，不执行后续添加操作\n",
    "        even_list.append(num)\n",
    "    return even_list\n",
    "\n",
    "# 测试\n",
    "raw_data = [2, 5, 8, 11, 14, 17]\n",
    "result = filter_even(raw_data)\n",
    "print(f\"过滤后的偶数列表：{result}\")  # 输出：[2, 8, 14]\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "## 四、适用场景与设计原则\n",
    "\n",
    "| 控制语句 | 典型场景 | 设计原则 |\n",
    "|----------|----------|----------|\n",
    "| `break`  | - 提前终止无效循环（如找到目标值）<br>- 避免无意义的计算（如检测到错误） | 优先使用`break`减少循环次数，提升性能 |\n",
    "| `continue` | - 过滤无效迭代（如跳过非法数据）<br>- 分离「必要操作」与「可选操作」 | 用`continue`简化嵌套条件，提高代码可读性 |\n",
    "\n",
    "---\n",
    "\n",
    "## 五、常见陷阱与规避\n",
    "\n",
    "### 5.1 陷阱1：`break`/`continue`作用域错误\n",
    "**现象**：在嵌套循环中，`break`仅终止内层循环，导致外层循环继续执行。\n",
    "**示例**：\n",
    "```python\n",
    "for i in range(3):\n",
    "    for j in range(3):\n",
    "        if j == 1:\n",
    "            break  # 仅终止内层循环\n",
    "        print(f\"i={i}, j={j}\")\n",
    "# 输出：i=0,j=0；i=1,j=0；i=2,j=0\n",
    "```\n",
    "**规避**：使用标志变量或`else`子句明确控制外层循环：\n",
    "```python\n",
    "found = False\n",
    "for i in range(3):\n",
    "    for j in range(3):\n",
    "        if j == 1:\n",
    "            found = True\n",
    "            break\n",
    "        print(f\"i={i}, j={j}\")\n",
    "    if found:\n",
    "        break  # 显式终止外层循环\n",
    "```\n",
    "\n",
    "### 5.2 陷阱2：`continue`后的代码未被跳过\n",
    "**现象**：`continue`后仍有未缩进的代码，导致逻辑错误。\n",
    "**示例**（错误代码）：\n",
    "```python\n",
    "for num in [1, 2, 3]:\n",
    "    if num == 2:\n",
    "        continue\n",
    "    print(num)  # 输出：1,3（正确）\n",
    "    print(\"已处理\")  # 输出：已处理（错误，num=2时应跳过）\n",
    "```\n",
    "**规避**：严格检查缩进，确保`continue`后无同层级代码：\n",
    "```python\n",
    "for num in [1, 2, 3]:\n",
    "    if num == 2:\n",
    "        continue\n",
    "    print(num)\n",
    "    print(\"已处理\")  # num=2时，此两行均被跳过\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "## 六、个人总结\n",
    "\n",
    "`break`与`continue`是Python循环控制的「精准工具」，其核心价值在于：\n",
    "1. **性能优化**：`break`可提前终止无效循环，减少不必要的计算；\n",
    "2. **逻辑清晰**：`continue`通过跳过无效迭代，分离核心逻辑与过滤逻辑；\n",
    "3. **错误处理**：结合条件判断，可在循环中快速响应异常（如`break`退出错误循环）。\n",
    "\n",
    "使用时需注意：\n",
    "- 嵌套循环中明确`break`的作用域；\n",
    "- 避免`continue`后残留未缩进代码；\n",
    "- 优先用`for-else`结构处理「循环正常结束」的场景（如未找到目标值）。\n",
    "\n",
    "掌握`break`与`continue`的本质区别和适用场景，是编写高效、易维护循环代码的关键。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 七、报数游戏\n",
    "1-100中，数字中带7或者7的倍数，跳过报数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "报数：1\n",
      "报数：2\n",
      "报数：3\n",
      "报数：4\n",
      "报数：5\n",
      "报数：6\n",
      "报数：8\n",
      "报数：9\n",
      "报数：10\n",
      "报数：11\n",
      "报数：12\n",
      "报数：13\n",
      "报数：15\n",
      "报数：16\n",
      "报数：18\n",
      "报数：19\n",
      "报数：20\n",
      "报数：22\n",
      "报数：23\n",
      "报数：24\n",
      "报数：25\n",
      "报数：26\n",
      "报数：29\n",
      "报数：30\n",
      "报数：31\n",
      "报数：32\n",
      "报数：33\n",
      "报数：34\n",
      "报数：36\n",
      "报数：38\n",
      "报数：39\n",
      "报数：40\n",
      "报数：41\n",
      "报数：43\n",
      "报数：44\n",
      "报数：45\n",
      "报数：46\n",
      "报数：48\n",
      "报数：50\n",
      "报数：51\n",
      "报数：52\n",
      "报数：53\n",
      "报数：54\n",
      "报数：55\n",
      "报数：58\n",
      "报数：59\n",
      "报数：60\n",
      "报数：61\n",
      "报数：62\n",
      "报数：64\n",
      "报数：65\n",
      "报数：66\n",
      "报数：68\n",
      "报数：69\n",
      "报数：80\n",
      "报数：81\n",
      "报数：82\n",
      "报数：83\n",
      "报数：85\n",
      "报数：86\n",
      "报数：88\n",
      "报数：89\n",
      "报数：90\n",
      "报数：92\n",
      "报数：93\n",
      "报数：94\n",
      "报数：95\n",
      "报数：96\n",
      "报数：99\n",
      "报数：100\n"
     ]
    }
   ],
   "source": [
    "def skip_number_game():\n",
    "    \"\"\"\n",
    "    实现1-100报数游戏：数字含7或为7的倍数时跳过\n",
    "    :return: 无返回值，直接打印有效报数\n",
    "    \"\"\"\n",
    "    for num in range(1, 101):  # 遍历1到100的所有整数\n",
    "        # 条件1：数字是7的倍数（能被7整除）\n",
    "        condition1 = num % 7 == 0\n",
    "        # 条件2：数字的字符串形式包含'7'（如17、70）\n",
    "        condition2 = '7' in str(num)\n",
    "\n",
    "        if condition1 or condition2:\n",
    "            continue  # 满足任一条件时跳过本次迭代\n",
    "\n",
    "        # 未触发continue时，正常报数\n",
    "        print(f\"报数：{num}\")\n",
    "\n",
    "# 执行游戏\n",
    "skip_number_game()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ai",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
